#include <YafridngRenderManagerI.h>

YafridngRenderManagerI::YafridngRenderManagerI(string file, 
					       string path,
					       int width,
					       int height,
					       TZones& zones,
					       ResultManagerPtr& resultManager,
					       Controller* c) : _file(file),
								_path(path),
								_zones(zones),
								_width(width),
								_height(height),
								_rendered(0),
								_resultManager(resultManager),
								_control(c)
{
  for(int i = 0; i < _zones.size(); i++){
    renderInfo temp;
    temp.status = NOT_RENDERED;
    _renderedZones.push_back(temp);
  }
}

::Ice::Int YafridngRenderManagerI::queryZone(const ::std::string& nodeId, 
					     const ::Ice::Current& c)
{
  Lock sync(*this);
  int sleep = 0;
  for(int i = 0; i < _zones.size(); i++){
    if(_renderedZones.at(i).status == NOT_RENDERED){
      _renderedZones.at(i).status = RENDERING;
      _renderedZones.at(i).start = IceUtil::Time::now();
      _renderedZones.at(i).renderer = nodeId;
      _control->setWorkUnit(nodeId, i);
      _control->setStatus(nodeId, "RENDERING");
      return i;
    }
    if(_renderedZones.at(i).status == RENDERING){
      sleep = SLEEP;
      _control->setStatus(nodeId, "SLEEPING");
    }
  }

  if(sleep == SLEEP)
    return sleep;

  return END;
}

void YafridngRenderManagerI::updateZone_async(const AMD_YafridngRenderManager_updateZonePtr& cb,
					      ::Ice::Int zone, 
					      const ::std::string& fileName,
					      const ::Yafridng::FilePrx& f,
					      const ::Ice::Current& c)
{
  int num = 1000 * 1024;
  Lock sync(*this);

  _renderedZones.at(zone).end = IceUtil::Time::now();
  cout << endl << "Zone: " << zone << endl;
  cout << "\tRenderer: " << _renderedZones.at(zone).renderer;
  cout << "\tRendering Time = " << (_renderedZones.at(zone).end - _renderedZones.at(zone).start).toSecondsDouble() << endl;

  FileManager fm(_path + fileName, f, "wb");
  _resultManager->add(cb, _width, _height, _zones.at(zone), _path + fileName, fm);
  _rendered += 1;

  if(_rendered == _zones.size())
    _resultManager->lastZone();

  _renderedZones.at(zone).status = RENDERED;
}

void YafridngRenderManagerI::cancelRender(const ::std::string& nodeId)
{
  Lock sync(*this);
  bool found = false;
  for(int i = 0; i < _renderedZones.size() && !found; i++)
    {
      if(_renderedZones.at(i).status == RENDERING && _renderedZones.at(i).renderer == nodeId){
	cout << "Desmarcando la zona renderizada por: " << nodeId << endl;
	_renderedZones.at(i).status = NOT_RENDERED;
	_control->setStatus(nodeId, "DOWN");
	found = true;
      }
    }
}
